﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using WeiboPlus.Common;
using WeiboPlus.Models;
using WeiboPlus.Shell.ViewModel;

namespace WeiboPlus.Shell.Views
{
    public partial class StatusDetailView : PhoneApplicationPage
    {
        int lastSelectedIndex = 0;
        private bool hasInit = false;
        ScrollViewer svComments;
        StatusDetailViewModel _vm;

        public StatusDetailView()
        {
            InitializeComponent();

            Loaded += new RoutedEventHandler(StatusDetailView_Loaded);

            //pivot.Visibility = System.Windows.Visibility.Collapsed;
        }

        void _vm_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            switch (e.PropertyName)
            {
                case "Loading":
                    if (_vm.Loading)
                    {
                        progressIndicator.IsIndeterminate = true;
                        HideMenu();
                    }
                    else
                    {
                        progressIndicator.IsIndeterminate = false;
                        PopulateMenu();
                    }
                    break;
                case "PivotSelectedIndex":

                    if (PhoneApplicationService.Current.State.ContainsKey("SDPivotSelectedIndex"))
                        PhoneApplicationService.Current.State["SDPivotSelectedIndex"] = _vm.PivotSelectedIndex;
                    else
                        PhoneApplicationService.Current.State.Add("SDPivotSelectedIndex", _vm.PivotSelectedIndex);

                    if (!_vm.HasRetweet)
                    {
                        if (_vm.PivotSelectedIndex == 2)
                        {
                            if (lastSelectedIndex == 1)
                            {
                                _vm.PivotSelectedIndex = 0;
                            }
                            else if (lastSelectedIndex == 0)
                            {
                                _vm.PivotSelectedIndex = 1;
                            }
                            return;
                        }
                        else
                        {
                            lastSelectedIndex = _vm.PivotSelectedIndex;
                        }
                    }

                    SetAppIconButton(_vm.PivotSelectedIndex);
                    break;
                default:
                    break;
            }
        }

        private void SetAppIconButton(int p)
        {
            ApplicationBar.Buttons.Clear();
            ApplicationBarIconButton refreash_home;
            switch (p)
            {
                case 0:
                    var back = new ApplicationBarIconButton(new Uri("/Images/AppBarIcons/appbar.back.rest.png", UriKind.Relative)) { Text = AppResx.GoBackText };
                    back.Click += new EventHandler(back_Click);
                    ApplicationBar.Buttons.Add(back);
                    var send = new ApplicationBarIconButton(new Uri("/Images/AppBarIcons/appbar_repost.png", UriKind.Relative)) { Text = AppResx.ForwardText };
                    send.Click += new EventHandler(send_Click);
                    ApplicationBar.Buttons.Add(send);
                    var comment = new ApplicationBarIconButton(new Uri("/Images/AppBarIcons/appbar_comment.png", UriKind.Relative)) { Text = AppResx.CommentText };
                    comment.Click += new EventHandler(to_comment_Click);
                    ApplicationBar.Buttons.Add(comment);

                    break;
                case 1:
                    send = new ApplicationBarIconButton(new Uri("/Images/AppBarIcons/appbar_comment.png", UriKind.Relative)) { Text = AppResx.CommentText };
                    send.Click += new EventHandler(comment_Click);
                    ApplicationBar.Buttons.Add(send);

                    //refreash_home = new ApplicationBarIconButton(new Uri("/Images/AppBarIcons/refresh.png", UriKind.Relative)) { Text = AppResx.RefreshText };
                    //refreash_home.Click += new EventHandler(refreash_comment_Click);
                    //ApplicationBarIconButton more_comment = new ApplicationBarIconButton(new Uri("/Images/AppBarIcons/next.png", UriKind.Relative)) { Text = AppResx.RefreshText };
                    //refreash_home.Click += new EventHandler(refreash_comment_Click);
                    //more_comment.Click += new EventHandler(more_comment_Click);
                    //ApplicationBar.Buttons.Add(refreash_home);
                    //ApplicationBar.Buttons.Add(more_comment);
                    break;
                case 2:
                    send = new ApplicationBarIconButton(new Uri("/Images/AppBarIcons/appbar_comment.png", UriKind.Relative)) { Text = AppResx.CommentText };
                    send.Click += new EventHandler(ocomment_Click);
                    ApplicationBar.Buttons.Add(send);

                    //refreash_home = new ApplicationBarIconButton(new Uri("/Images/AppBarIcons/refresh.png", UriKind.Relative)) { Text = AppResx.RefreshText };
                    //refreash_home.Click += new EventHandler(refreash_comment_Click);
                    //ApplicationBarIconButton more_comment = new ApplicationBarIconButton(new Uri("/Images/AppBarIcons/next.png", UriKind.Relative)) { Text = AppResx.RefreshText };
                    //refreash_home.Click += new EventHandler(refreash_comment_Click);
                    //more_comment.Click += new EventHandler(more_comment_Click);
                    //ApplicationBar.Buttons.Add(refreash_home);
                    //ApplicationBar.Buttons.Add(more_comment);
                    break;
                default:
                    break;
            }
        }

        void more_comment_Click(object sender, EventArgs e)
        {
            if (_vm.MoreComments.CanExecute() && this.commentsList.Items.Count >= 10)
                _vm.MoreComments.Execute();

            //throw new NotImplementedException();
        }

        private void PopulateMenu()
        {
            if (!this.ApplicationBar.IsVisible)
                this.ApplicationBar.IsVisible = true;
            //throw new NotImplementedException();
        }

        private void HideMenu()
        {
            if (this.ApplicationBar.IsVisible)
                this.ApplicationBar.IsVisible = false;
            //throw new NotImplementedException();
        }

        void StatusDetailView_Loaded(object sender, RoutedEventArgs e)
        {
            if (hasInit)
                return;
            hasInit = true;
            var q = NavigationContext.QueryString.FirstOrDefault();

            if (q.Key != null && PhoneApplicationService.Current.State.ContainsKey(q.Key))
            {
                var status = PhoneApplicationService.Current.State[q.Key] as SNSStatus;

                if (status != null)
                {
                    _vm = new StatusDetailViewModel(status);
                    DataContext = _vm;
                }
                else
                    goto LABEL_ERR;
            }
            else
                goto LABEL_ERR;

            _vm.OnNextPagePerformed += () =>
            {
                if (svComments == null && _vm.Comments.Count > 0)
                {
                    svComments = FindScrollViewerRecursive(commentsList);
                    svComments.ManipulationCompleted += (s, eventArgs) =>
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            if (eventArgs.TotalManipulation.Translation.Y < -100 && svComments.VerticalOffset >= svComments.ScrollableHeight)
                            {
                                _vm.MoreComments.Execute();

                            }
                            else if (eventArgs.TotalManipulation.Translation.Y > 100 && svComments.VerticalOffset <= 0)
                            {
                                _vm.RefreshComments.Execute();
                            }
                        });
                    };
                }


            };
            _vm.OnRefreshed += (item) =>
            {
                if (item != null)
                    this.commentsList.ScrollIntoView(item);
                _vm.OnRefreshed = null;
            };
            _vm.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(_vm_PropertyChanged);
            ApplicationBar = new ApplicationBar() { Opacity = .5 };

            SetAppIconButton(0);

            if (!_vm.HasRetweet)
            {
                ocomment_item.Header = "";
                ocomment_item.Content = "";
                ocomment_item = null;
            }
            return;
        //throw new NotImplementedException();
        LABEL_ERR:
            throw new Exception("status no found");
        }

        void back_Click(object sender, EventArgs e)
        {
            if (NavigationService.CanGoBack)
                NavigationService.GoBack();
            //throw new NotImplementedException();
        }

        void send_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tbRepost.Text))
            {
                var result = MessageBox.Show(AppResx.ConfirmEmptyForwardContentText, AppResx.ForwardText, MessageBoxButton.OKCancel);
                if (result == MessageBoxResult.Cancel)
                {
                    tbRepost.Focus();
                    return;
                }
                else if (result == MessageBoxResult.OK)
                {
                    _vm.RepostText = AppResx.ForwardText;
                }
            }
            else
            {
                _vm.RepostText = tbRepost.Text;
            }

            if (_vm.Repost.CanExecute())
                _vm.Repost.Execute();
            sv.Focus();
        }

        void comment_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tbReply.Text))
            {
                MessageBox.Show(AppResx.WarnNoCommentContentText);
                tbReply.Focus();
                return;
            }
            _vm.CommentText = tbReply.Text;
            if (_vm.Reply.CanExecute())
                _vm.Reply.Execute();
            _vm.OnRefreshed += (item) =>
            {
                if (item != null)
                    this.commentsList.ScrollIntoView(item);
                _vm.OnRefreshed = null;
            };
            commentsList.Focus();
        }

        void ocomment_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tbReplyToOriginal.Text))
            {
                MessageBox.Show(AppResx.WarnNoCommentContentText);
                tbReplyToOriginal.Focus();
                return;
            }
            _vm.CommentTextToOriginal = tbReplyToOriginal.Text;
            if (_vm.ReplyToOriginal.CanExecute())
                _vm.ReplyToOriginal.Execute();
            _vm.OnRefreshed += (item) =>
            {
                if (item != null)
                    this.ocommentsList.ScrollIntoView(item);
                _vm.OnRefreshed = null;
            };
            ocommentsList.Focus();
        }

        void to_comment_Click(object sender, EventArgs e)
        {
            if (_vm.PivotSelectedIndex != 1)
            {
                _vm.PivotSelectedIndex = 1;
                tbReply.Focus();
            }
        }

        void refreash_comment_Click(object sender, EventArgs e)
        {
            if (_vm.RefreshComments.CanExecute())
                _vm.RefreshComments.Execute();
            else
                return;
        }


        private ScrollViewer FindScrollViewerRecursive(UIElement element)
        {

            int childCount = VisualTreeHelper.GetChildrenCount(element);

            for (int i = 0; i < childCount; i++)
            {

                if (VisualTreeHelper.GetChild(element, i) as ScrollViewer != null)
                {

                    return (VisualTreeHelper.GetChild(element, i) as ScrollViewer);

                }
                else
                    FindScrollViewerRecursive(VisualTreeHelper.GetChild(element, i) as UIElement);
            }
            return null;
        }

        private void OnTapToUserHome(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var user = _vm.Item.User;
            var key = user.AccountName + "=" + user.AccountID;

            if (PhoneApplicationService.Current.State.ContainsKey(key))
            {
                PhoneApplicationService.Current.State.Remove(key);
            }

            PhoneApplicationService.Current.State.Add(key, user);
            NavigationService.Navigate(new Uri("/Views/UserHomeView.xaml?" + key, UriKind.Relative));
        }

        private void TextBlock_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (_vm.Item.RetweetedStatus != null)
            {
                var status = _vm.Item.RetweetedStatus;
                var key = status.Id.ToString();

                if (PhoneApplicationService.Current.State.ContainsKey(key))
                {
                    PhoneApplicationService.Current.State.Remove(key);
                }

                PhoneApplicationService.Current.State.Add(key, status);
                NavigationService.Navigate(new Uri("/Views/StatusDetailView.xaml?" + key, UriKind.RelativeOrAbsolute));
            }
        }

        private void tbRetUserName_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var user = _vm.Item.RetweetedStatus.User;
            var key = user.AccountName + "=" + user.AccountID;

            if (PhoneApplicationService.Current.State.ContainsKey(key))
            {
                PhoneApplicationService.Current.State.Remove(key);
            }

            PhoneApplicationService.Current.State.Add(key, user);
            NavigationService.Navigate(new Uri("/Views/UserHomeView.xaml?" + key, UriKind.Relative));
        }

        private void User_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var statusVM = sender as SNSStatusViewModel;
            if (statusVM == null)
                return;

            var user = statusVM.Item.User;
            var key = user.AccountName + "=" + user.AccountID;

            if (PhoneApplicationService.Current.State.ContainsKey(key))
            {
                PhoneApplicationService.Current.State.Remove(key);
            }

            PhoneApplicationService.Current.State.Add(key, user);
            NavigationService.Navigate(new Uri("/Views/UserHomeView.xaml?" + key, UriKind.Relative));
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (PhoneApplicationController.Current.AppSetting.EnableOrientationChange)
            {
                SupportedOrientations = SupportedPageOrientation.PortraitOrLandscape;
            }
            else
            {
                var orientation = (SupportedPageOrientation)PhoneApplicationController.Current.AppSetting.CurrentSupportedOrientation;
                this.SupportedOrientations = orientation;
                this.Orientation = (PageOrientation)PhoneApplicationController.Current.AppSetting.CurrentOrientation;
            }
        }

        protected override void OnOrientationChanged(OrientationChangedEventArgs e)
        {
            base.OnOrientationChanged(e);
            if (PhoneApplicationController.Current.AppSetting.EnableOrientationChange)
            {
                switch (e.Orientation)
                {
                    case PageOrientation.LandscapeLeft:
                        pivot.SetValue(FrameworkElement.MarginProperty, new Thickness(0, 0, 70, 0));
                        break;
                    case PageOrientation.LandscapeRight:
                        pivot.SetValue(FrameworkElement.MarginProperty, new Thickness(70, 0, 0, 0));
                        break;
                    case PageOrientation.PortraitDown:
                        pivot.SetValue(FrameworkElement.MarginProperty, new Thickness(0, 0, 0, 70));
                        break;
                    case PageOrientation.PortraitUp:
                        pivot.SetValue(FrameworkElement.MarginProperty, new Thickness(0, 0, 0, 70));
                        break;
                    default:
                        break;
                }
            }
        }

        private void commentsList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                var statusVM = (e.AddedItems[0] as SNSStatusViewModel);
                if (statusVM != null)
                {
                    _vm.CommentText = AppResx.ReplyText + " @" + statusVM.Item.User.AccountName + " :";
                }
            }
        }

        private void ocommentsList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                var statusVM = (e.AddedItems[0] as SNSStatusViewModel);
                if (statusVM != null)
                {
                    _vm.CommentTextToOriginal = AppResx.ReplyText + " @" + statusVM.Item.User.AccountName + " :";
                }
            }
        }
    }
}
